package com.game.sec;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.game.globalconst.JsonUtil;
import com.game.globalconst.Result;
import com.game.utils.SecStringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 在发送body之前进行 body内容加密
 * 
 * @author ZGame
 *
 *
 */
@ControllerAdvice
@Slf4j
public class SecResponseBodyAdvice implements ResponseBodyAdvice<Object> {

	@Value("${security.open}")
	private boolean openSecurity;

	/**
	 * 是否开启response拦截功能
	 */
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return openSecurity;
	}

	/**
	 * response加密
	 */
	@Override
	public String beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		try {
			if (body instanceof Result) {
				return SecStringUtil.secString(JsonUtil.parseToString(body));
			} else {
				log.info("body:=============   " + body);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String result = JsonUtil.parseToString(body);
		log.info("返回未加密内容:" + result);
		return result;
	}
}
